var express = require('express');
var router = express.Router();
var db = require('../../config/db')
var bcrypt = require('bcryptjs')
var jwt = require('jsonwebtoken');
var config = require('../../schema/config')//导入密钥配置文件

exports.login = (req,res)=>{
    var userinfo = req.body
    var sql = `select * from user_info where name=?`
    db.query(sql, userinfo.name, (err, results)=>{
        if(err) return res.cc('500', err)
        if(results.length !== 1) return res.cc('404', '登录失败')
        if(results[0].password !== userinfo.password) return res.cc('404', '登录失败')

        //密码验证,使用加密的话，就应该有解密
        //var compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
        //if(compareResult) return res.cc('404', '登录失败')
        //生成token
        // res.send({ //返回前端信息
        //     status: 200,
        //     message: '登录成功',
        // })
        var user = {...results[0], password:'', phone: '',avatar: ''}//把里边的某些键值清空
        //加密
        var tokenStr = jwt.sign(user, config.jwtSecrectKey, {expiresIn: config.expiresIn})//加密对象，加密解密的密钥，有效期
        //db.release()
        res.send({ //返回前端信息
            status: 200,
            message: '登录成功',
            token: 'Bearer '+tokenStr,//方便前端解析
        })
    })
}